package com.hjimi.ski.view.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.media.Image;
import android.media.ImageReader;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.atech.glcamera.camera.Camera2FrameCallback;
import com.atech.glcamera.camera.Camera2Wrapper;
import com.atech.glcamera.camera.CameraUtil;
import com.atech.glcamera.render.GLByteFlowRender;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.gongw.remote.communication.CommunicationKey;
import com.gongw.remote.communication.slave.CommandReceiver;
import com.gongw.remote.search.DeviceSearchResponser;
import com.hjimi.ski.R;
import com.hjimi.ski.app.MyApplication;
import com.hjimi.ski.bean.DeviceMqttBean;
import com.hjimi.ski.bean.InitDeviceBean;
import com.hjimi.ski.bean.SyncImageListBean;
import com.hjimi.ski.config.Constant;
import com.hjimi.ski.iView.InitDeviceIView;
import com.hjimi.ski.iView.SyncImageListIView;
import com.hjimi.ski.iView.UpdateIpIView;
import com.hjimi.ski.presenter.InitDevicePresenter;
import com.hjimi.ski.presenter.SyncImageListPresenter;
import com.hjimi.ski.presenter.UpdateIpPresenter;
import com.hjimi.ski.utils.ColorConvertUtil;
import com.hjimi.ski.utils.DiscoverNetIpUtil;
import com.hjimi.ski.utils.DownLoadPool;
import com.hjimi.ski.utils.ImageListUtil;
import com.hjimi.ski.utils.InitUtil;
import com.hjimi.ski.utils.JsonParseUtil;
import com.hjimi.ski.utils.MqttJsonToBeanUtil;
import com.hjimi.ski.utils.Mutils;
import com.hjimi.ski.utils.NetworkPostTask;
import com.hjimi.ski.utils.NetworkTask;
import com.hjimi.ski.utils.SDFileHelper;
import com.hjimi.ski.utils.SdcardUtils;
import com.hjimi.ski.utils.SpUtil;
import com.hjimi.ski.utils.ToastUtils;
import com.hjimi.ski.utils.update.AllDialogShowStrategy;
import com.hjimi.ski.utils.update.NotificationDownloadCreatorMandatory;
import com.hjimi.ski.utils.update.NotificationUpdateCreatorMandatory;
import com.hjimi.ski.utils.update.OkhttpCheckWorker;
import com.hjimi.ski.utils.update.OkhttpDownloadWorker;
import com.hjimi.ski.view.event.MqttDeviceInfoEvent;
import com.hjimi.ski.view.event.MqttEvent;

import com.hjimi.ski.view.service.MqttService;
import com.hjimi.ski.view.service.MyImageService;
import com.hjimi.ski.view.widget.ProgressDialog;
import com.hjimi.ski.view.widget.VideoPopup;
import com.shizhefei.view.largeimage.LargeImageView;
import com.shizhefei.view.largeimage.remote.EventReceiver;
import com.shizhefei.view.largeimage.remote.IReceiveMonitor;
import com.shuyu.waveview.AudioPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.lzh.framework.updatepluginlib.UpdateBuilder;

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import xyz.doikki.videocontroller.StandardVideoController;
import xyz.doikki.videoplayer.player.VideoView;

import static android.view.Surface.ROTATION_180;
import static com.atech.glcamera.render.ByteFlowRender.IMAGE_FORMAT_I420;
import static com.hjimi.ski.app.MyApplication.jingdongfangSDK;

/**
 * Created By 孙岩
 * on 2023/3/20
 */
public class NewImageActivity extends BaseActivity implements SyncImageListIView, Camera2FrameCallback, IReceiveMonitor, UpdateIpIView, InitDeviceIView {
    private LargeImageView imageView;
    private int position = 0;
    //获取设备下的图片列表
    private SyncImageListPresenter syncImageListPresenter;
    private InitDevicePresenter initDevicePresenter;
    //重置ip
    private UpdateIpPresenter updateIpPresenter;
    private List<SyncImageListBean.DataBean> list;
    public MyThread myThread;
    private Camera2Wrapper mCamera2Wrapper;
    private RelativeLayout mRootView;
    GLSurfaceView mGLSurfaceView;
    GLByteFlowRender mByteFlowRender;
    private int mSampleSelectedIndex = 0;
    private long exitTime = 0L;
    private VideoView player;
    private EventReceiver receiver;
    //默认缩放大小
    private float defaultSize = 1;
    //旋转角度
    private int angle = 180;
    private RequestOptions requestOptions;
    //播放音乐
    private AudioPlayer audioText = null;
    //初始化数据
    private InitDeviceBean.DataBean systemBean = null;
    //默认轮播时间
    private int loopTime = 15;
    Handler handler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("CheckResult")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);
            Log.d("sunyan", SdcardUtils.getImageInPhone(position, list));
            if (list.get(position).getBgm_config().isIs_open()) {
                //设置背景音乐
                showMusic(SdcardUtils.getAudioInPhone(position, list), list.get(position).getBgm_config().isIs_loop());
            } else {
                stopMusic();
            }
            if (Mutils.isNetworkAvailable()) {
                showCard(position);
            }
        }
    };


    public Set<String> runSet = new HashSet<>();
    private Map<String, String> action = new HashMap<>();

    private Intent intent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_image);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        action.put("init", "initDevice");
        action.put("sync", "getSyncImageList");

        initView();
        initData();
        startMqttService();
        syncImageListPresenter = new SyncImageListPresenter();
        syncImageListPresenter.attachView(this);

        initDevicePresenter = new InitDevicePresenter();
        initDevicePresenter.attachView(this);

        //重置ip
        updateIpPresenter = new UpdateIpPresenter();
        updateIpPresenter.attachView(this);

        if (Camera.getNumberOfCameras() != 0) {
            mGLSurfaceView = new GLSurfaceView(NewImageActivity.this);
            RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(320, 240);
            mRootView.addView(mGLSurfaceView, p);
            mByteFlowRender = new GLByteFlowRender();
            mByteFlowRender.init(mGLSurfaceView);
            mByteFlowRender.loadShaderFromAssetsFile(mSampleSelectedIndex, getResources());
            mCamera2Wrapper = new Camera2Wrapper(NewImageActivity.this);
            mCamera2Wrapper.startCamera();

            Log.d("wangweili", "有摄像头");

        } else {
            Log.d("wangweili", "无摄像头");
        }

        receiver = EventReceiver.getInstance();

        if (!SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getString("update", "1").equals("1")) {
            update();
        }


        updateIp();

        requestOptions = new RequestOptions()
                .error(R.mipmap.default_no_work)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);

        Log.d("sunyan", "mac====" + getMac());

        if (Mutils.isNetworkAvailable()) {
            NetworkPostTask networkPostTask = new NetworkPostTask(new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    switch (msg.what) {
                        case 1:
                            try {
                                JSONObject obj = new JSONObject(msg.obj.toString());
                                if (obj.getInt("code") == 200) {
                                    JSONObject object = new JSONObject(obj.getString("data"));

                                    JSONObject turnConfigObj = new JSONObject(object.getString("turn_config"));
                                    InitDeviceBean.DataBean.TurnConfigBean turnConfigBean = new InitDeviceBean.DataBean.TurnConfigBean(
                                            JsonParseUtil.getBoolean(turnConfigObj, "is_open"),
                                            JsonParseUtil.getStr(turnConfigObj, "start_time"),
                                            JsonParseUtil.getStr(turnConfigObj, "end_time"),
                                            JsonParseUtil.getStr(turnConfigObj, "weeks")
                                    );
                                    JSONObject bgmConfigObj = new JSONObject(object.getString("bgm_config"));
                                    InitDeviceBean.DataBean.BgmConfigBean bgmConfigBean = new InitDeviceBean.DataBean.BgmConfigBean(
                                            JsonParseUtil.getBoolean(bgmConfigObj, "is_open"),
                                            JsonParseUtil.getInt(bgmConfigObj, "bgm_id"),
                                            JsonParseUtil.getStr(bgmConfigObj, "bgm_url"),
                                            JsonParseUtil.getBoolean(bgmConfigObj, "is_loop")
                                    );
                                    InitDeviceBean.DataBean bean = new InitDeviceBean.DataBean(
                                            JsonParseUtil.getStr(object, "mac"),
                                            JsonParseUtil.getStr(object, "sn"),
                                            JsonParseUtil.getInt(object, "screen_id"),
                                            JsonParseUtil.getInt(object, "size_id"),
                                            JsonParseUtil.getInt(object, "screen_angle_id"),
                                            JsonParseUtil.getInt(object, "buffer_id"),
                                            JsonParseUtil.getInt(object, "camera_angle_id"),
                                            JsonParseUtil.getInt(object, "is_camera"),
                                            JsonParseUtil.getStr(object, "ip"),
                                            JsonParseUtil.getInt(object, "is_carousel"),
                                            JsonParseUtil.getInt(object, "carousel_seconds"),
                                            JsonParseUtil.getInt(object, "is_gesture"),
                                            JsonParseUtil.getInt(object, "device_id"),
                                            JsonParseUtil.getInt(object, "device_info_id"),
                                            JsonParseUtil.getStr(object, "phone"),
                                            JsonParseUtil.getStr(object, "token"),
                                            turnConfigBean,
                                            bgmConfigBean
                                    );
                                    showInitDevice(bean);
                                } else if (obj.getInt("code") == 202) {
                                    show202();
                                } else {
                                    ToastUtils.show(obj.getString("msg"));
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                    }
                    super.handleMessage(msg);
                }
            });
            networkPostTask.execute("mac=" + SpUtil.getInstance(NewImageActivity.this).getString(Constant.MAC, "") + "&" + "sn=" + SpUtil.getInstance(NewImageActivity.this).getString(Constant.SN, "") + "&" + "ip=" + DiscoverNetIpUtil.getIpAddress(NewImageActivity.this));


            NetworkTask networkTask = new NetworkTask(new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    switch (msg.what) {
                        case 1:
                            SpUtil.getInstance(getContext()).putString(Constant.IMAGE_JSON, msg.obj.toString());
                            try {
                                JSONObject obj = new JSONObject(msg.obj.toString());
                                if (obj.getInt("code") == 200) {
                                    JSONArray array = new JSONArray(obj.getString("data"));
                                    List<SyncImageListBean.DataBean> list = new ArrayList<>();

                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject object = new JSONObject(array.get(i).toString());
                                        JSONObject bgmConfigObj = new JSONObject(object.getString("bgm_config"));
                                        SyncImageListBean.DataBean.BgmConfigBean bgmConfigBean = new SyncImageListBean.DataBean.BgmConfigBean(
                                                JsonParseUtil.getBoolean(bgmConfigObj, "is_open"),
                                                JsonParseUtil.getInt(bgmConfigObj, "bgm_id"),
                                                JsonParseUtil.getString(bgmConfigObj, "bgm_url"),
                                                JsonParseUtil.getBoolean(bgmConfigObj, "is_loop")
                                        );
                                        JSONObject cardConfigObj = new JSONObject(object.getString("card_config"));
                                        SyncImageListBean.DataBean.CardConfigBean cardConfigBean = new SyncImageListBean.DataBean.CardConfigBean(
                                                JsonParseUtil.getBoolean(cardConfigObj, "is_open"),
                                                JsonParseUtil.getString(cardConfigObj, "title"),
                                                JsonParseUtil.getString(cardConfigObj, "desc"),
                                                JsonParseUtil.getString(cardConfigObj, "author"),
                                                JsonParseUtil.getString(cardConfigObj, "period"),
                                                JsonParseUtil.getBoolean(cardConfigObj, "is_narration"),
                                                JsonParseUtil.getBoolean(cardConfigObj, "is_qr"),
                                                JsonParseUtil.getString(cardConfigObj, "qr_url"),
                                                JsonParseUtil.getInt(cardConfigObj, "carousel_seconds")
                                        );
                                        SyncImageListBean.DataBean bean = new SyncImageListBean.DataBean(
                                                JsonParseUtil.getInt(object, "id"),
                                                JsonParseUtil.getStr(object, "name"),
                                                JsonParseUtil.getStr(object, "imageUrl"),
                                                JsonParseUtil.getStr(object, "thumbUrl"),
                                                JsonParseUtil.getStr(object, "qrUrl"),
                                                JsonParseUtil.getInt(object, "artwork_id"),
                                                bgmConfigBean,
                                                cardConfigBean,
                                                JsonParseUtil.getBoolean(object, "is_default")
                                        );
                                        list.add(bean);
                                    }
                                    showSyncImage(list);
                                } else {
                                    ToastUtils.show(obj.getString("msg"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                    }
                    super.handleMessage(msg);
                }
            });
            networkTask.execute(SpUtil.getInstance(this).getString(Constant.DEVICE_ID, "0"));

        } else {
            showNoWifi();
        }

    }

    //启动mqttservice
    private void startMqttService() {
        intent = new Intent(this, MqttService.class);
        startService(intent);
    }

    //无网络情况
    private void showNoWifi() {
        //获取本地初始化
        String noWifiInit = SpUtil.getInstance(getContext()).getString(Constant.INIT_JSON, "");
        try {
            JSONObject obj = new JSONObject(noWifiInit);
            if (obj.getInt("code") == 200) {
                JSONObject object = new JSONObject(obj.getString("data"));

                JSONObject turnConfigObj = new JSONObject(object.getString("turn_config"));
                InitDeviceBean.DataBean.TurnConfigBean turnConfigBean = new InitDeviceBean.DataBean.TurnConfigBean(
                        JsonParseUtil.getBoolean(turnConfigObj, "is_open"),
                        JsonParseUtil.getStr(turnConfigObj, "start_time"),
                        JsonParseUtil.getStr(turnConfigObj, "end_time"),
                        JsonParseUtil.getStr(turnConfigObj, "weeks")
                );
                JSONObject bgmConfigObj = new JSONObject(object.getString("bgm_config"));
                InitDeviceBean.DataBean.BgmConfigBean bgmConfigBean = new InitDeviceBean.DataBean.BgmConfigBean(
                        JsonParseUtil.getBoolean(bgmConfigObj, "is_open"),
                        JsonParseUtil.getInt(bgmConfigObj, "bgm_id"),
                        JsonParseUtil.getStr(bgmConfigObj, "bgm_url"),
                        JsonParseUtil.getBoolean(bgmConfigObj, "is_loop")
                );
                InitDeviceBean.DataBean bean = new InitDeviceBean.DataBean(
                        JsonParseUtil.getStr(object, "mac"),
                        JsonParseUtil.getStr(object, "sn"),
                        JsonParseUtil.getInt(object, "screen_id"),
                        JsonParseUtil.getInt(object, "size_id"),
                        JsonParseUtil.getInt(object, "screen_angle_id"),
                        JsonParseUtil.getInt(object, "buffer_id"),
                        JsonParseUtil.getInt(object, "camera_angle_id"),
                        JsonParseUtil.getInt(object, "is_camera"),
                        JsonParseUtil.getStr(object, "ip"),
                        JsonParseUtil.getInt(object, "is_carousel"),
                        JsonParseUtil.getInt(object, "carousel_seconds"),
                        JsonParseUtil.getInt(object, "is_gesture"),
                        JsonParseUtil.getInt(object, "device_id"),
                        JsonParseUtil.getInt(object, "device_info_id"),
                        JsonParseUtil.getStr(object, "phone"),
                        JsonParseUtil.getStr(object, "token"),
                        turnConfigBean,
                        bgmConfigBean
                );
                if (bean.getIs_carousel() == 0) {//轮播关闭
                    Log.d("sunyan", "设置为单图");
                    SpUtil.getInstance(NewImageActivity.this).putBoolean(Constant.MODE, false);
                } else {//轮播开启
                    Log.d("sunyan", "设置为轮播");
                    SpUtil.getInstance(NewImageActivity.this).putBoolean(Constant.MODE, true);
                }
                loopTime = bean.getCarousel_seconds();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //获取本地的列表
        String noWifiJson = SpUtil.getInstance(this).getString(Constant.IMAGE_JSON, "");
        try {
            JSONObject obj = new JSONObject(noWifiJson);
            if (obj.getInt("code") == 200) {
                JSONArray array = new JSONArray(obj.getString("data"));
                List<SyncImageListBean.DataBean> list = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = new JSONObject(array.get(i).toString());
                    JSONObject bgmConfigObj = new JSONObject(object.getString("bgm_config"));
                    SyncImageListBean.DataBean.BgmConfigBean bgmConfigBean = new SyncImageListBean.DataBean.BgmConfigBean(
                            JsonParseUtil.getBoolean(bgmConfigObj, "is_open"),
                            JsonParseUtil.getInt(bgmConfigObj, "bgm_id"),
                            JsonParseUtil.getString(bgmConfigObj, "bgm_url"),
                            JsonParseUtil.getBoolean(bgmConfigObj, "is_loop")
                    );
                    JSONObject cardConfigObj = new JSONObject(object.getString("card_config"));
                    SyncImageListBean.DataBean.CardConfigBean cardConfigBean = new SyncImageListBean.DataBean.CardConfigBean(
                            JsonParseUtil.getBoolean(cardConfigObj, "is_open"),
                            JsonParseUtil.getString(cardConfigObj, "title"),
                            JsonParseUtil.getString(cardConfigObj, "desc"),
                            JsonParseUtil.getString(cardConfigObj, "author"),
                            JsonParseUtil.getString(cardConfigObj, "period"),
                            JsonParseUtil.getBoolean(cardConfigObj, "is_narration"),
                            JsonParseUtil.getBoolean(cardConfigObj, "is_qr"),
                            JsonParseUtil.getString(cardConfigObj, "qr_url"),
                            JsonParseUtil.getInt(cardConfigObj, "carousel_seconds")
                    );
                    SyncImageListBean.DataBean bean = new SyncImageListBean.DataBean(
                            JsonParseUtil.getInt(object, "id"),
                            JsonParseUtil.getStr(object, "name"),
                            JsonParseUtil.getStr(object, "imageUrl"),
                            JsonParseUtil.getStr(object, "thumbUrl"),
                            JsonParseUtil.getStr(object, "qrUrl"),
                            JsonParseUtil.getInt(object, "artwork_id"),
                            bgmConfigBean,
                            cardConfigBean,
                            JsonParseUtil.getBoolean(object, "is_default")
                    );
                    list.add(bean);
                }
                this.list = list;


//                //设置背景音乐
//                if (SpUtil.getInstance(this).getString(Constant.IS_MUSIC_OPEN, "").equals("1")) {//已设置背景音乐
//                    if (SpUtil.getInstance(this).getString(Constant.IS_MUSIC_OPEN_LOOP, "").equals("1")) {//背景音乐设置为轮播
//                        if (SdcardUtils.getAudioPathFromSD().size() != 0) {
//                            showMusic(SdcardUtils.getAudioPathFromSD().get(0), true);
//                        } else {
//                            showMusic(SdcardUtils.getAudioPathFromSD().get(0), false);
//                        }
//                    } else {
//                        showMusic(SdcardUtils.getAudioPathFromSD().get(0), false);
//                    }
//                }
                position = 0;
                if (SpUtil.getInstance(NewImageActivity.this).getBoolean(Constant.MODE, false)) {

                    Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);
                    lunxun(list);
                } else {
                    //设置图片
                    Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);
                }

                if (list.get(position).getBgm_config().isIs_open()) {
                    //设置背景音乐
                    showMusic(SdcardUtils.getAudioInPhone(position, list), list.get(position).getBgm_config().isIs_loop());
                } else {
                    stopMusic();
                }

                //播放视频
                if(SpUtil.getInstance(NewImageActivity.this).getString(Constant.IS_VIDEO_OPEN,"1").equals("1")){
                    player.setVisibility(View.VISIBLE);
                    setOneVideoBanner(SpUtil.getInstance(NewImageActivity.this).getString(Constant.DEVICE_VIDEO_URL,""));
                    Log.d("sunyan","无网络-----------"+SpUtil.getInstance(NewImageActivity.this).getString(Constant.DEVICE_VIDEO_URL,""));
                }else{
                    player.setVisibility(View.GONE);
                }
            } else {
                ToastUtils.show(obj.getString("msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        mRootView = findViewById(R.id.root_view);
        imageView = findViewById(R.id.imageView);
        player = findViewById(R.id.player);
    }

    //初始化数据回调
    @Override
    public void showInitDevice(InitDeviceBean.DataBean bean) {
        if (bean != null) {

            //旋转角度
            switch (bean.getCamera_angle_id()) {
                case 1:
                    angle = 180;
                    break;
                case 2:
                    angle = 270;
                    break;
                case 3:
                    angle = 90;
                    break;
                case 4:
                    angle = 0;
                    break;
                default:
                    angle = 180;
                    break;
            }

            NewImageActivity.this.systemBean = bean;

            loopTime = bean.getCarousel_seconds();
            if (bean.getIs_carousel() == 0) {//轮播关闭
                SpUtil.getInstance(NewImageActivity.this).putBoolean(Constant.MODE, false);
            } else {//轮播开启
                SpUtil.getInstance(NewImageActivity.this).putBoolean(Constant.MODE, true);
            }

            if (bean.getIs_gesture() == 0) {//手势关闭
                SpUtil.getInstance(NewImageActivity.this).putString(Constant.isShowShi, "1");
            } else {//手势开启
                SpUtil.getInstance(NewImageActivity.this).putString(Constant.isShowShi, "");
            }

//            if (bean.getBgm_config().isIs_open()) {
//                SpUtil.getInstance(NewImageActivity.this).putString(Constant.IS_MUSIC_OPEN, "1");
//                if (bean.getBgm_config().isIs_loop()) {
//                    SpUtil.getInstance(NewImageActivity.this).putString(Constant.IS_MUSIC_OPEN_LOOP, "1");
//                } else {
//                    SpUtil.getInstance(NewImageActivity.this).putString(Constant.IS_MUSIC_OPEN_LOOP, "0");
//                }
//                Log.d("sunyan", "isIs_open---------" + bean.getBgm_config().getBgm_url());
//
//                //播放 音乐
//                showMusic(bean.getBgm_config().getBgm_url(), bean.getBgm_config().isIs_loop());
//                if (SdcardUtils.getAudioPathFromSD().size() == 0) {
//                    //下载音乐到本地
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            SDFileHelper.downloadAudioFromNetwork(bean.getBgm_config().getBgm_url(), Mutils.md5(bean.getBgm_config().getBgm_url()) + ".mp3");
//                        }
//                    }).start();
//                } else {
//                    if (!SdcardUtils.getAudioPathFromSD().get(0).equals(("/storage/emulated/0/Pic/audio/") + Mutils.md5(bean.getBgm_config().getBgm_url()) + ".mp3")) {
//                        SdcardUtils.deleteFileAudio();
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                SDFileHelper.downloadAudioFromNetwork(bean.getBgm_config().getBgm_url(), Mutils.md5(bean.getBgm_config().getBgm_url()) + ".mp3");
//                            }
//                        }).start();
//                    }
//                }
//            } else {
//                SpUtil.getInstance(NewImageActivity.this).putString(Constant.IS_MUSIC_OPEN, "");
//                if (audioText != null) {
//                    audioText.pause();
//                    audioText.stop();
//                }
//            }
        }


    }

    //数据列表回调
    @SuppressLint("CheckResult")
    @Override
    public void showSyncImage(List<SyncImageListBean.DataBean> list) {
        if (list.size() != 0) {
            NewImageActivity.this.list = list;
            position = 0;
            if (SpUtil.getInstance(NewImageActivity.this).getBoolean(Constant.MODE, false)) {
                if (list.size() == 1) {
                    Glide.with(MyApplication.getInstance().getApplicationContext()).load(list.get(position).getImageUrl()).apply(requestOptions).into(imageView);
                } else {
                    Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);
                    lunxun(list);
                }
            } else {
                //设置图片
                Glide.with(MyApplication.getInstance().getApplicationContext()).load(list.get(position).getImageUrl()).apply(requestOptions).into(imageView);
            }

            updateIp();

            if (list.get(position).getBgm_config().isIs_open()) {
                //设置背景音乐
                showMusic(list.get(position).getBgm_config().getBgm_url(), list.get(position).getBgm_config().isIs_loop());
            } else {
                stopMusic();
            }
            showCard(position);
            Intent intent = new Intent(NewImageActivity.this, MyImageService.class);
            intent.putExtra("beanList", (Serializable) list);
            startService(intent);
        }

        if(SpUtil.getInstance(NewImageActivity.this).getString(Constant.IS_VIDEO_OPEN,"1").equals("1")){
            player.setVisibility(View.VISIBLE);
            setOneVideoBanner(SpUtil.getInstance(NewImageActivity.this).getString(Constant.DEVICE_VIDEO_URL,""));
        }else{
            player.setVisibility(View.GONE);
        }
    }

    //轮询
    private void lunxun(List<SyncImageListBean.DataBean> list) {
        if (myThread == null) {
            myThread = new MyThread(list);
            new Thread(myThread).start();
        }
    }

    // 2、新建一个实现Runnable接口的线程类
    class MyThread implements Runnable {
        private List<SyncImageListBean.DataBean> newList;

        public MyThread(List<SyncImageListBean.DataBean> list) {
            this.newList = list;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(newList.get(position).getCard_config().getCarousel_seconds() == 0 ? loopTime * 1000 : newList.get(position).getCard_config().getCarousel_seconds() * 1000);

                    if (position == newList.size() - 1) {
                        position = 0;
                    } else {
                        position = position + 1;
                    }
                    if (SpUtil.getInstance(NewImageActivity.this).getBoolean(Constant.MODE, false)) {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //收到命令
    private void initData() {
        DeviceSearchResponser.open(this, SpUtil.getInstance(this).getInt(Constant.device_info_id, 0) + "", SpUtil.getInstance(this).getString(Constant.SN, ""));
        CommandReceiver.open(new CommandReceiver.CommandListener() {
            @Override
            public String onReceive(String command) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("sunyan", "收到命令+" + command);
                        try {
                            JSONObject object = new JSONObject(command);
                            if (object.getInt("status") == 2) {//解绑
                                unBindSync();
                            } else if (object.getInt("status") == 3) {//同步
                                doRun("sync");
                            } else if (object.getInt("status") == 4) {//切换
                                //切换不需要画屏操作
                            } else if (object.getInt("status") == 5) {//单图
                                Log.d("wangweili", "设置为单图");
                                SpUtil.getInstance(NewImageActivity.this).putBoolean(Constant.MODE, false);

                                doRun("init");
                            } else if (object.getInt("status") == 6) {//轮播
                                Log.d("wangweili", "设置为轮播");
                                SpUtil.getInstance(NewImageActivity.this).putBoolean(Constant.MODE, true);
                                doRun("init");
                            } else if (object.getInt("status") == 7) {//开启手势放大缩小控制画屏
                                doRun("sync");
                                receiver.setReceive_monitor(NewImageActivity.this);
                                Log.d("wangweili", "startReceiver()");
                                if (!receiver.isRunning()) {
                                    receiver.startReceiver();
                                }
                            } else if (object.getInt("status") == 8) {//关闭
                                Log.d("wangweili", "关闭手势()");
                                SpUtil.getInstance(NewImageActivity.this).putString(Constant.isShowShi, "1");
                                doRun("init");
                            } else if (object.getInt("status") == 9) {//开启
                                Log.d("wangweili", "开启手势()");
                                SpUtil.getInstance(NewImageActivity.this).putString(Constant.isShowShi, "");
                                doRun("init");
                            } else if (object.getInt("status") == 10) {//删除作品
                                Log.d("wangweili", "拿到了删除作品的消息------------------------------------------");
                                doRun("sync");
                            } else if (object.getInt("status") == 11) {//开启视频
                                downDeleteRes(object.getString("image"));
                            } else if (object.getInt("status") == 12) {//关闭视频

                                stopVideo();

                                if (audioText != null) {
                                    audioText.play();
                                }

                            } else if (object.getInt("status") == 13) {//首页滑动以后执行的操作
                                Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getPathFromId(object.getInt("id"))).apply(requestOptions).into(imageView);
                            } else if (object.getInt("status") == 14) {//屏幕设置页面保存以后的同步操作
                                doRun("init");
                                doRun("sync");
                            } else if (object.getInt("status") == 15) {//单张图片设置轮播时间以及卡片信息后的同步操作
                                doRun("sync");
                            } else if (object.getInt("status") == 16) {//视频

                            } else if (object.getInt("status") == 17) {//首页滑动
                                //给本地position赋值传过来的position
                                position = object.getInt("id");
                                Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);
                                if (list.get(position).getBgm_config().isIs_open()) {
                                    //设置背景音乐
                                    showMusic(SdcardUtils.getAudioInPhone(position, list), list.get(position).getBgm_config().isIs_loop());
                                } else {
                                    stopMusic();
                                }

                            } else if (object.getInt("status") == 18) {//轮播前移轮播后移，排序
                                doRun("sync");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return CommunicationKey.RESPONSE_OK +
                        (SpUtil.getInstance(NewImageActivity.this).getString(Constant.IS_VIDEO_OPEN, "")) +
                        CommunicationKey.EOF;
            }
        });
    }

    private void downDeleteRes(String paths) {
        Log.d("sunyan","url="+paths);
        String path = Mutils.md5(paths) + ".mp4";
        List<String> list = new ArrayList<>();
        list.clear();
        List<String> outputPathList = new ArrayList<>();
        outputPathList.clear();
        //线下的集合
        List<String> onDown = SdcardUtils.getImageNameFromSD();
        Log.d("sunyan","onDown======================="+onDown.toString());
        Log.d("sunyan","path=================="+path);
       boolean isDown = onDown.contains(path);

        if (isDown) {
            Log.d("sunyan","list是空");
            setOneVideoBanner("/storage/emulated/0/Pic/app/" + path);
        } else {
            list.add(paths);
            Log.d("sunyan","list是"+list.toString());
            outputPathList.add("/storage/emulated/0/Pic/app/" + path);
            //执行下载操作
            ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.show();

            new DownLoadPool(new Handler(Looper.getMainLooper()) {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void handleMessage(@NonNull Message msg) {
                    switch (msg.what) {
                        case 1:
                            progressDialog.dismissProgress();
                            Log.d("sunyan", "下载完成");
                           //播放
                            setOneVideoBanner("/storage/emulated/0/Pic/app/" + path);
                            break;
                        case 2:
                            Log.d("sunyan", "下载失败");
                            break;
                        case 3:
                            Log.d("sunyan", "磁盘空间不足" + msg.obj);
                            break;
                        case 4:
                            Log.d("sunyan", "url错误" + msg.obj);
                            //url错误
                            MqttService.publish(msg.obj.toString(), Constant.RES_RESULT + SpUtil.getInstance(NewImageActivity.this).getString(Constant.DEVICE_ID, ""));
                            break;
                        case 50:
                            progressDialog.setmText("" + msg.obj);
                            break;
                        case 100:
                            progressDialog.setProgress(Integer.parseInt(msg.obj + ""));
                            break;
                    }
                    super.handleMessage(msg);
                }
            }).downloadImages(list, outputPathList);
        }
    }

    private Timer timer;
    private TimerTask task;
    private long delay = 500; // 延迟时间，默认为1秒

    private void doRun(String status) {

        if (!status.equals("")) {
            runSet.add(status);
        }

        stopTimer(); // 先停止之前的定时器任务

        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                // 任务执行的逻辑
                Log.d("sunyan", "TimerTask-----run----");
                ArrayList<String> runList = new ArrayList<String>(runSet);
                for (int i = 0; i < runList.size(); i++) {
                    Log.d("sunyan", "for---------------------" + i);
                    String a = action.get(runList.get(i));
                    Log.d("sunyan", "a=" + a);
                    assert a != null;
                    switch (a) {
                        case "getSyncImageList":
                            NetworkTask networkTask = new NetworkTask(new Handler(Looper.getMainLooper()) {
                                @Override
                                public void handleMessage(@NonNull Message msg) {
                                    switch (msg.what) {
                                        case 1:
                                            SpUtil.getInstance(getContext()).putString(Constant.IMAGE_JSON, msg.obj.toString());
                                            Log.d("sunyan", "-----sync=" + msg.obj.toString());
                                            showSyncImage(ImageListUtil.getImageList(msg.obj.toString()));
                                            break;
                                    }
                                    super.handleMessage(msg);
                                }
                            });
                            networkTask.execute(SpUtil.getInstance(NewImageActivity.this).getString(Constant.DEVICE_ID, "0"));
                            break;
                        case "initDevice":
                            NetworkPostTask networkPostTask = new NetworkPostTask(new Handler(Looper.getMainLooper()) {
                                @Override
                                public void handleMessage(@NonNull Message msg) {
                                    switch (msg.what) {
                                        case 1:
                                            SpUtil.getInstance(getContext()).putString(Constant.INIT_JSON, msg.obj.toString());
                                            Log.d("sunyan", "-----init=" + msg.obj.toString());
                                            showInitDevice(InitUtil.getInitDevice(msg.obj.toString()));
                                            break;
                                    }
                                    super.handleMessage(msg);
                                }
                            });
                            networkPostTask.execute("mac=" + SpUtil.getInstance(NewImageActivity.this).getString(Constant.MAC, "") + "&" + "sn=" + SpUtil.getInstance(NewImageActivity.this).getString(Constant.SN, "") + "&" + "ip=" + DiscoverNetIpUtil.getIpAddress(NewImageActivity.this));
                            break;
                    }
                    if (i == runList.size() - 1) {
                        runSet.clear();
                    }
                }
            }
        };

        timer.schedule(task, delay);
    }


    public void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onPreviewFrame(byte[] data, int width, int height) {

    }

    @Override
    public void onCaptureFrame(byte[] data, int width, int height) {
    }

    @Override
    public void onPreviewFrame(ImageReader ir) {
        Image image = ir.acquireLatestImage();
        if (image != null) {
            byte[] mYuvBytes = CameraUtil.YUV_420_888_data(image);

            int width = image.getWidth();
            int height = image.getHeight();
            //TODO 开启回显模式
            mByteFlowRender.setRenderFrame(IMAGE_FORMAT_I420, mYuvBytes, width, height);
            mByteFlowRender.requestRender();

            byte[] rgb = new byte[width * height * 3];
            ColorConvertUtil.yuv420pToRGB(mYuvBytes, width, height, rgb);
            int result;
            byte[] rgba_r;
            if (jingdongfangSDK.InitState) {
                ByteBuffer bb = ByteBuffer.allocateDirect(width * height * 3);
//                if (angle == 0) {//不旋转
//                    bb.put(rgb);
//                    result = jingdongfangSDK.GetGesture(bb, 3, width, height, 3 * width, 0);
//                } else if (angle == 270) {//旋转270
//                    if (DeviceSearchResponser.getData().equals("HiDPTAndroid Hi3751V352")) {//21.5寸
//                        //21.5寸画屏旋转270
//                        rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 2);
//                        bb.put(rgba_r);
//                        result = jingdongfangSDK.GetGesture(bb, 3, width, height, 3 * width, 0);
//
//                    } else {//65寸
//                        //65寸画屏旋转270
//                        rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 1);
//                        bb.put(rgba_r);
//                        result = jingdongfangSDK.GetGesture(bb, 3, height, width, 3 * height, 0);
//                    }
//                } else if(angle==90){
//                    //旋转90
//                    rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 3);
//                    bb.put(rgba_r);
//                    result = jingdongfangSDK.GetGesture(bb, 3, width, height, 3 * width, 0);
//                } else {
//                    //旋转180
//                    rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 3);
//                    bb.put(rgba_r);
//                    result = jingdongfangSDK.GetGesture(bb, 3, height, width, 3 * height, 0);
//                }

                switch (angle) {
                    case 0://上
//                        Log.d("sunyan","0------------------0");
                        rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 1);
                        bb.put(rgba_r);
                        result = jingdongfangSDK.GetGesture(bb, 3, height, width, 3 * height, 0);
                        break;
                    case 90://右
//                        Log.d("sunyan","90------------------90");
                        rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 2);
                        bb.put(rgba_r);
                        result = jingdongfangSDK.GetGesture(bb, 3, width, height, 3 * width, 0);
                        break;
                    case 270://左
//                        Log.d("sunyan","270------------------270");
                        rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 0);
                        bb.put(rgba_r);
                        result = jingdongfangSDK.GetGesture(bb, 3, width, height, 3 * width, 0);
                        break;
                    default://下
//                        Log.d("sunyan","angle------------------angle"+angle);
                        rgba_r = Mutils.rgbBytesRotateClockwise(rgb, width, height, 3);
                        bb.put(rgba_r);
                        result = jingdongfangSDK.GetGesture(bb, 3, height, width, 3 * height, 0);
                        break;
                }

                if (result != -1) {
                    if (SpUtil.getInstance(NewImageActivity.this).getString(Constant.isShowShi, "").equals("")) {
                        if (SpUtil.getInstance(NewImageActivity.this).getBoolean(Constant.MODE, false)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.show("请先切换为单图模式");
                                }
                            });
                        } else {
                            if (list.size() > 1) {
                                Log.d("sunyan", "执行手势操作");
                                setImageResult(result);
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.show("请保证同步两张图以上再进行手势操作！");
                                    }
                                });
                            }

                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.show("请设置开启手势设置");
                            }
                        });
                    }
                }
            } else {
                Log.d("sunyan", "啥啊这是");
            }
            image.close();

            //String yuvPath = FileUtil.SAVE_DIR + System.currentTimeMillis() + ".MP4";
            //FileUtil.saveBytes(rgba_r, yuvPath);
        } else {
            Log.d("sunyan", "image=null");
        }
    }

    //收到手势操作结果后的操作
    private void setImageResult(int result) {
        if (System.currentTimeMillis() - exitTime > 500) {
            // 将系统当前的时间赋值给exitTime
            exitTime = System.currentTimeMillis();
            if (result == 1) {//右滑
                Log.d("sunyan:", "result=" + result + "-------position=" + position);
                if (position == list.size() - 1) {//说明是最后一张
                    position = 0;
                    Log.d("sunyan", "position========0置位4");
                } else {
                    position = position + 1;
                }
                runOnUiThread(new Runnable() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void run() {
                        Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);

                        if (list.get(position).getBgm_config().isIs_open()) {
                            //设置背景音乐
                            showMusic(SdcardUtils.getAudioInPhone(position, list), list.get(position).getBgm_config().isIs_loop());
                        } else {
                            stopMusic();
                        }
                        showCard(position);
                    }
                });
            } else if (result == 2) {//左滑
                Log.d("sunyan:", "result=" + result + "-------position=" + position);
                if (position == 0) {//说明是第一张
                    position = list.size() - 1;
                } else {
                    position = position - 1;
                }
                runOnUiThread(new Runnable() {
                    @SuppressLint("CheckResult")
                    @Override
                    public void run() {
                        Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);
                        if (list.get(position).getBgm_config().isIs_open()) {
                            //设置背景音乐
                            showMusic(SdcardUtils.getAudioInPhone(position, list), list.get(position).getBgm_config().isIs_loop());
                        } else {
                            stopMusic();
                        }

                        showCard(position);
                    }
                });
            } else if (result == 9) {//放大
                defaultSize = defaultSize + 0.1f;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setScale(defaultSize, 500, 1000);
                    }
                });

            } else if (result == 10) {//缩小
                defaultSize = defaultSize - 0.1f;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setScale(defaultSize, 500, 1000);
                    }
                });
            }
        }
    }

    @Override
    public void onEventReceive(JSONObject obj) {
        JSONObject param = null;
        try {
            int cmd = obj.getInt("command");
            switch (cmd) {
                case 502:
                    receiver.setReceive_monitor(null);
                    Log.d("wangweili", "stopReceiver()");
                    receiver.stopReceiver();

                    break;
                case 503:
                    Log.d("wangweili:", "缩放()13123123123123");
                    runOnUiThread(new Runnable() {
                        @SuppressLint("CheckResult")
                        @Override
                        public void run() {
                            do_event(obj);
                        }
                    });
                    break;
                case 504:
                    param = obj.getJSONObject("parameters");
                    String url = param.getString("url"); // 这里可以下载图片，不实现了
                    break;
                default:
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void do_event(JSONObject obj) {
        JSONObject param = null;
        try {
            param = obj.getJSONObject("parameters");
            String event_name = param.getString("event_name");
            if (event_name.equals("simpleOnGestureListener.onDoubleTap")) {
                double f = param.getDouble("newscale");
                int x = param.getInt("x");
                int y = param.getInt("y");
                imageView.smoothScale((float) f, x, y);
            } else if (event_name.equals("simpleOnGestureListener.onDown")) {
                imageView.stopScrollAnimation();
            } else if (event_name.equals("simpleOnGestureListener.onScroll")) {
                double distancex = param.getInt("distancex");
                double distancey = param.getInt("distancey");
                int scrollx = param.getInt("scrollx");
                int scrolly = param.getInt("scrolly");
                int scrollrangex = param.getInt("scrollrangex");
                int scrollrangey = param.getInt("scrollrangey");
                imageView.wrap_overScrollByCompat((int) distancex, (int) distancey, scrollx, scrolly,
                        scrollrangex, scrollrangex);
            } else if (event_name.equals("onScaleGestureListener.onScale")) {
                double newscale = param.getDouble("newscale");
                int focusx = param.getInt("focusx");
                int focusy = param.getInt("focusy");
                imageView.setScale((float) newscale, focusx, focusy);
            } else if (event_name.equals("simpleOnGestureListener.onFling")) {
                double velocityx = param.getInt("velocityx");
                double velocityy = param.getInt("velocityy");
                imageView.wrap_fling((int) -velocityx, (int) -velocityx);
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    //重置ip回调
    @Override
    public void showUpdateIpResult() {

    }


    @Override
    public void show202() {

    }


    private void update() {
        String mCurVersionName = Mutils.getLocalVersionName(this);
        int mCurVersionCode = Mutils.getLocalVersion(this);
        UpdateBuilder builder = UpdateBuilder.create();

        // 根据各项是否选择使用默认配置进行使用更新。
        builder.setCheckWorker(OkhttpCheckWorker.class);
        builder.setUpdateStrategy(new AllDialogShowStrategy());
        builder.setDownloadNotifier(new NotificationDownloadCreatorMandatory());
        builder.setCheckNotifier(new NotificationUpdateCreatorMandatory(builder, mCurVersionName, mCurVersionCode, new NotificationUpdateCreatorMandatory.NotificationUpdateCreatorI() {
            @Override
            public void onClick(int button) {
                if (button == 0) {

                }
            }

            @Override
            public void isNotMandatory() {//不是强制升级

            }
        }));
        builder.setDownloadWorker(OkhttpDownloadWorker.class);
        builder.check();
    }

    //重置ip
    private void updateIp() {
        if (!SpUtil.getInstance(this).getString(Constant.thisIp, "").equals(DiscoverNetIpUtil.getIpAddress(this))) {//两个ip不相同
            updateIpPresenter.updateIp(SpUtil.getInstance(NewImageActivity.this).getString(Constant.DEVICE_ID, ""), this);
        }
    }

    /*** 获取手机的MAC地址* @return String*/
    public String getMac() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address").toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return macSerial;
    }

    public static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    public static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    private void showCard(int position) {
        SyncImageListBean.DataBean dbean = list.get(position);
        RelativeLayout lu = findViewById(R.id.layout_card);
//        LinearLayout llo = findViewById(R.id.layout_QR);
        if (dbean.getCard_config().isIs_open()) {
            lu.setVisibility(View.VISIBLE);
//            llo = findViewById(R.id.layout_QR);
//            if (dbean.getCard_config().isIs_qr()) {
//                llo.setVisibility(View.VISIBLE);
//                ImageView imgQR = findViewById(R.id.imgQR);
//                Glide.with(MyApplication.getInstance().getApplicationContext()).load(list.get(position).getQrUrl()).apply(requestOptions).into(imgQR);
//            } else {
//                llo.setVisibility(View.GONE);
//            }
            TextView tvTitle = findViewById(R.id.tv_pic_title);
            TextView tvAuthor = findViewById(R.id.tv_pic_author);
            TextView tvDesc = findViewById(R.id.tv_pic_desc);
            if (tvTitle != null) {
                tvTitle.setText(dbean.getCard_config().getTitle());
            }
            if (tvAuthor != null) {
                tvAuthor.setText("作者：" + dbean.getCard_config().getAuthor());
            }
            if (tvDesc != null) {
                tvDesc.setText(dbean.getCard_config().getDesc());
            }
        } else {
            lu.setVisibility(View.GONE);
//            llo.setVisibility(View.GONE);
        }
    }

    private void stopMusic() {
        if (audioText != null) {
            audioText.pause();
            audioText.stop();
        }
    }

    //播放音乐
    @SuppressLint("HandlerLeak")
    private void showMusic(String url, boolean isLooper) {
        Log.d("sunyan", "开始播放音乐" + "------11111------本地音乐地址为" + url);
        if (audioText != null) {
            audioText.pause();
            audioText.stop();
        }
        audioText = new AudioPlayer(NewImageActivity.this, new Handler() {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://text播放结束
                        Log.d("sunyan", "开始播放音乐" + "------------播放结束" + url);
                        if (isLooper) {
                            audioText.playUrl(url);
                        }
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
                        Log.d("sunyan", "开始播放音乐" + "------------播放开始" + url);
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        Log.d("sunyan", "开始播放音乐" + "------------播放错误" + url);
                        break;
                }
            }
        });
        audioText.playUrl(url);
    }

    //解绑以后的操作
    private void unBindSync() {
        SpUtil.getInstance(NewImageActivity.this).putString(Constant.IS_VIDEO_OPEN, "");
        SpUtil.getInstance(NewImageActivity.this).putString(Constant.DEVICE_VIDEO_URL, "");
        stopVideo();
        if (audioText != null) {
            audioText.play();
        }
        SpUtil.getInstance(NewImageActivity.this).putString(Constant.DEVICE_ID, "");
        SpUtil.getInstance(NewImageActivity.this).putBoolean(Constant.MODE, false);
        //删除本地图片数据
        SdcardUtils.deleteFile();
        //删除本地音频数据
        SdcardUtils.deleteFileAudio();
        DeviceSearchResponser.close();
        Intent intent = new Intent(NewImageActivity.this, UnBindActivity.class);
        startActivity(intent);

        NewImageActivity.this.finish();
    }

    //收到mqtt返回的数据
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dataEvent(MqttEvent event) {
        DeviceMqttBean deviceMqttBean = MqttJsonToBeanUtil.setJsonToBean(event.getMsg());
        if (deviceMqttBean != null) {
            switch (deviceMqttBean.getCode()) {
                case 1://绑定
                    break;
                case 2://解绑
                    unBindSync();
                    stopService(intent);
                    break;
                case 3://同步，设置为当前展示
                    doRun("sync");
                    break;
                case 14://屏幕设置
                    doRun("init");
                    doRun("sync");
                    break;
                case 15://卡片信息
                    doRun("sync");
                    break;
                case 10://删除作品
                    doRun("sync");
                    break;
                case 18://排序，迁移后移
                    doRun("sync");
                    break;
                case 13://首页滑动
                case 17:
                    //给本地position赋值传过来的position
                    position = deviceMqttBean.getId();
                    Glide.with(MyApplication.getInstance().getApplicationContext()).load(SdcardUtils.getImageInPhone(position, list)).apply(requestOptions).into(imageView);
                    if (list.get(position).getBgm_config().isIs_open()) {
                        //设置背景音乐
                        showMusic(SdcardUtils.getAudioInPhone(position, list), list.get(position).getBgm_config().isIs_loop());
                    } else {
                        stopMusic();
                    }
                    break;
                case 11://开启视频
                    Log.d("sunyan","开启视频");
                    downDeleteRes( deviceMqttBean.getUrl());
                    break;
                case 12://关闭视频
                    Log.d("sunyan","关闭视频");
                    stopVideo();
                    if (audioText != null) {
                        audioText.play();
                    }
                    break;
            }
        }
    }

    @Override
    protected void onPause() {
        stopVideo();
        if (audioText != null) {
            audioText.pause();
            audioText.stop();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        SpUtil.getInstance(this).putString(Constant.thisIp, "");
        EventReceiver receiver = EventReceiver.getInstance();
        receiver.setReceive_monitor(null);
        if (mCamera2Wrapper != null) {
            mCamera2Wrapper.stopCamera();
        }

        if (receiver.isRunning()) {
            receiver.stopReceiver();
        }

        if (audioText != null) {
            audioText.pause();
            audioText.stop();
        }
        super.onDestroy();
    }


    //单视频轮播
    private void setOneVideoBanner(String path) {
        SpUtil.getInstance(NewImageActivity.this).putString(Constant.IS_VIDEO_OPEN, "1");
        SpUtil.getInstance(NewImageActivity.this).putString(Constant.DEVICE_VIDEO_URL,path);
        if (systemBean != null) {
            if (systemBean.getBgm_config().isIs_open()) {
                if (audioText != null) {
                    audioText.pause();
                }
            }
        }
        SpUtil.getInstance(NewImageActivity.this).putString(Constant.isShowShi, "1");
//        if (videoPopup == null) {
//            videoPopup = new VideoPopup(NewImageActivity.this, path);
//        } else {
//            videoPopup.startVideo(path, NewImageActivity.this);
//        }
//        videoPopup.setPopupWindowFullScreen(true);
//        videoPopup.showPopupWindow();
        player.setVisibility(View.VISIBLE);
        player.setUrl(path); //设置视频地址
        StandardVideoController controller = new StandardVideoController(this);
        controller.addDefaultControlComponent("", false);
        player.setVideoController(controller); //设置控制器
        //监听播放结束
        player.addOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {

            @Override
            public void onPlayStateChanged(int playState) {
                if (playState == VideoView.STATE_PLAYBACK_COMPLETED) {
                    player.release();
                    //重新设置数据
                    player.setUrl(path); //设置视频地址
                    player.setVideoController(controller);
                    //开始播放
                    player.start();
                } else if (playState == VideoView.STATE_ERROR) {
                    Log.d("sunyan", playState + "");
                }
            }
        });
        player.start(); //开始播放，不调用则不自动播放
    }

    public void stopVideo(){
        if(player!=null){
            player.release();
        }
    }
}
